package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*",filterName = "loginCheckFilter")
@Slf4j
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        log.info("本次请求放行:{}",url);
//        定义不需要处理的请求
        String[] urls = {"/employee/login"
                , "/employee/logout"
                , "/backend/**"
                ,"/front/**"
                , "/common/upload"
                , "/common/download"
                ,"/user/sendMsg"
                ,"/user/login"
        };
        for (String s : urls) {
            boolean match = ANT_PATH_MATCHER.match(s,url);
            if(match){
                chain.doFilter(servletRequest,servletResponse);
                return ;
            }
        }
        //判断登录状态，如果已登录，则直接放行
       Long employee = (Long) request.getSession().getAttribute("employee");
        if (employee !=null){
            BaseContext.setCurrentId(employee);
            chain.doFilter(servletRequest,servletResponse);
            log.info("已登录,登录信息:{}", employee);
            return;
        }
            log.info("用户未登录,返回登录");
            //写出到前端
        //4.2、判断登录状态，如果已登录，则直接放行
        Object userId = request.getSession().getAttribute("user");//获取session中的用户id
        if(userId != null) {
            //把当前登陆用户id设置到本地线程中
            BaseContext.setCurrentId((Long) userId);
            //session中用户id不为空，已登陆，直接放行
            chain.doFilter(request, response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
}
